package com.gs.spider.tq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;

/**
 * Created by TQ on 2017/5/24.
 */
public class HttpClientUtil {
    public String doPost(String url, Map<String, String> map, String charset) {
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = getHttpClient();
            httpPost = new HttpPost(url);
            //设置参数
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            Iterator iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, String> elem = (Entry<String, String>) iterator.next();
                list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
            }
            if (list.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
                httpPost.setEntity(entity);
            }
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, charset);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                //closeHttpClient(httpClient);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    public String login(String url, Map<String, String> map, CloseableHttpClient httpClient) {
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = getHttpClient();
            httpPost = new HttpPost(url);
            PostMethod post = new PostMethod();
            post.setRequestHeader("Connection", "keep-alive");
            //设置参数
            List<NameValuePair> list = new ArrayList<>();
            Iterator iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, String> elem = (Entry<String, String>) iterator.next();
                list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
            }
            if (list.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
                httpPost.setEntity(entity);
            }
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "UTF-8");
                    result = response.getHeaders("Set-Cookie")[0].getElements()[0].getValue();
                    Map<String, String> reqAttr = new HashMap<>();
                    reqAttr.put("start", "20");
                    reqAttr.put("limit", "20");
                    reqAttr.put("loadStore", "true");//&Token=" + result
                    String listResult = dcdPost("http://120.40.103.185:8899/UIProcessor?Table=Entity_SCGJ", reqAttr, httpClient);
                    System.out.println(listResult);
                    listResult = listResult.replaceAll("\"[^\":,]*\":[^\\(:,]*\\([^\\)]*\\),", "");
                    JSONObject obj = JSON.parseObject(listResult);

                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
        }
        return result;
    }

    public String dcdPost(String url, Map<String, String> map, CloseableHttpClient httpClient) {
        String result = null;
        HttpPost httpPost = null;
        try {
            httpPost = new HttpPost(url);
            //设置参数
            List<NameValuePair> list = new ArrayList<>();
            Iterator iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, String> elem = (Entry<String, String>) iterator.next();
                list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
            }
            if (list.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
                httpPost.setEntity(entity);
            }
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "UTF-8");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    public void testHeader() {
        HttpClient httpClient = new HttpClient(new SimpleHttpConnectionManager());
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(5000);
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        PostMethod post = new PostMethod("http://120.40.103.185:8899/login.do");
        post.addParameter("userId", "5150262");
        post.addParameter("pass", "xxfxxf");
        post.addParameter("validate", "login");
        post.setRequestHeader("Connection", "keep-alive");
        try {
            System.out.println(httpClient.executeMethod(post));

        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public CloseableHttpClient getHttpClient() {
        return HttpClients.createDefault();
    }

    public void closeHttpClient(CloseableHttpClient client) throws IOException {
        if (client != null) {
            client.close();
        }
    }

    public static void main(String[] args) {
        HttpClientUtil et = new HttpClientUtil();
        et.testHeader();
    }
}